package com.example.observerdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.observerdemo.observer.IObservable;
import com.example.observerdemo.observer.IObserver;
import com.example.observerdemo.observer.ObserverHolder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements IObserver {

    @BindView(R.id.txt_content)
    TextView txtContent;
    @BindView(R.id.btn_staff_manage)
    Button btnStaffManage;
    private int count = 8;

//    private EventObserver observer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

//        observer = new EventObserver();

        ObserverHolder.getInstance().register(this);
        txtContent.setText("有"+count+"位员工");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // FIXME Activity销毁的时候记得释放
        ObserverHolder.getInstance().unregister(this);
    }

    /**
     * 重写自 IObserver 的方法
     * @param observable  消息发布者
     * @param msg  发布的消息内容
     * @param flag 消息的类型标记
     */
    @Override
    public void onMessageReceived(IObservable observable, Object msg, int flag) {
        switch (flag) {
            case ObserverHolder.STAFF_ADD:  // 添加员工
                Log.e("DEVICE_ADD", (String) msg);
                count++;
                break;
            case ObserverHolder.STAFF_DELETE:  //删除员工
                Log.e("DEVICE_DELETE", (String) msg);
                count--;
                break;
        }
        txtContent.setText("还有"+count+"位员工");
    }

    @OnClick({R.id.txt_content, R.id.btn_staff_manage})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_staff_manage:
                startActivity(new Intent(this,StaffManageActivity.class));
                break;
        }
    }

    public class EventObserver  implements IObserver{
        /**
         * 重写自 IObserver 的方法
         * @param observable  消息发布者
         * @param msg  发布的消息内容
         * @param flag 消息的类型标记
         */
        @Override
        public void onMessageReceived(IObservable observable, Object msg, int flag) {
            switch (flag) {
                case ObserverHolder.STAFF_ADD:  // 添加员工
                    Log.e("DEVICE_ADD", (String) msg);
                    count++;
                    break;
                case ObserverHolder.STAFF_DELETE:  //删除员工
                    Log.e("DEVICE_DELETE", (String) msg);
                    count--;
                    break;
            }
            txtContent.setText("还有"+count+"位员工");
        }
    }

}
